const fs = require('fs');
const path = require('path');
const fse = require('fs-extra');
const xlsx = require('xlsx');

// 配置
const sourceDir = path.join(__dirname, 'directional_pics');  // 原始文件夹目录
const targetDir = path.join(__dirname, 'selected_pics');    // 目标文件夹
const excelFilePath = path.join(__dirname, 'all_score.csv'); // Excel 文件路径
const totalPicsToCopy = 7010;  // 要复制的文件夹数量

// 确保目标文件夹存在
fse.ensureDirSync(targetDir);

// 读取 Excel 数据并过滤符合条件的行
function readExcel() {
    const workbook = xlsx.readFile(excelFilePath);  // 读取 Excel 文件
    const sheetName = workbook.SheetNames[0];  // 假设读取第一个 sheet
    const worksheet = workbook.Sheets[sheetName];
    
    // 将 Excel 内容转换为 JSON 数组
    const rows = xlsx.utils.sheet_to_json(worksheet, { header: 1 });
  
    // 过滤出所有包含 ind 列的有效值的数据
    const filteredRows = rows.filter(row => row[1] && !isNaN(row[1])); // row[1] 应该是 ind 列
  
    // 提取出 ind 列的数据
    return filteredRows.slice(0, totalPicsToCopy).map(row => row[1]);  // 获取前 7000 个 ind 的值
}

// 根据 Excel 的排序复制文件夹
async function copyFolders() {
  try {
    // 读取 Excel 并过滤出需要的文件夹名
    const selectedFolderNames = readExcel();
    console.log(selectedFolderNames)
    // 遍历文件夹名并复制文件夹内的图片
    for (const folderName of selectedFolderNames) {
      const folderPath = path.join(sourceDir, folderName.toString());
      
      if (fs.existsSync(folderPath) && fs.statSync(folderPath).isDirectory()) {
        const targetFolderPath = path.join(targetDir, folderName.toString());
        
        // 创建目标文件夹
        fse.ensureDirSync(targetFolderPath);

        // 获取该文件夹内的所有图片文件
        const files = fs.readdirSync(folderPath);
        const imageFiles = files.filter(file => /\.(png|jpg|jpeg)$/i.test(file));  // 支持常见图片格式

        // 复制所有图片到目标文件夹
        for (const imageFile of imageFiles) {
          const sourceImagePath = path.join(folderPath, imageFile);
          const targetImagePath = path.join(targetFolderPath, imageFile);
          await fse.copy(sourceImagePath, targetImagePath);
        }

        console.log(`Copied images from folder: ${folderName}`);
      } else {
        console.log(`Folder not found or not a directory: ${folderName}`);
      }
    }

    console.log(`${totalPicsToCopy} folders have been copied to ${targetDir}`);
  } catch (error) {
    console.error('Error copying folders:', error);
  }
}

copyFolders();
